package com.emip.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import com.emip.bean.MenuDefBean;
import com.emip.bean.SiteBean;
import com.emip.bean.SiteItemBean;
import com.emip.bean.UserBean;
import com.emip.config.SysConfig;
import com.emip.config.SysParams;
import com.emip.service.MenuDefService;
import com.emip.service.SiteItemService;
import com.emip.service.UserService;

@Controller
@RequestMapping(value="/user")
public class LoginAction {

	private static Logger logger = Logger.getLogger(LoginAction.class);
	
	@Autowired
	UserService userService;
	
	@Autowired
	MenuDefService menuDefService;
	
	@Autowired
	protected SiteItemService itemService;
	
	@RequestMapping(value="/pre_login")
	public String index()
	{		
		return "/login";
	}
	
	@RequestMapping(value="/login")
	public ModelAndView login()
	//public ModelAndView login( @RequestParam("userid") String userid,@RequestParam("password") String password, HttpSession session)
	{	
		
//		logger.info("doing login...");
//		
//		
//		
//		UserBean user = userService.login(userid, password);
//		ModelAndView mav = new ModelAndView();		
//		
//		if(user!= null)
//		{
//			mav.setViewName("/main");
//			session.setAttribute("user", user);
//		}else
//		{
//			//mav.setViewName("/index");
//			mav.setViewName("/login_new");
//			mav.addObject("login", "fail");	
//		}							
//		return mav;
				
		ModelAndView mav = new ModelAndView();	
		mav.setViewName("/main");
		return mav;
	}	
	
	@RequestMapping(value="/logout")
	public void logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
		//询问
		
		
		if(session.getAttribute("user")!=null)//判断用户名是不是为空
		{
			session.removeAttribute("user");//注销
		}
		
		response.sendRedirect(request.getContextPath()+"/index.do");
	}
	
	@RequestMapping(value="/authorize")
	public @ResponseBody String authorizeUser(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session)
	{
		UserBean user = userService.login(username, password);
    	if (user!= null) {
    		session.setAttribute("user", user);
    		//set user's menu from its role, and set menus into session
    		//UserBean userBean = (UserBean)session.getAttribute("user");
    		//String roleName = userBean.getRole().getName();
    		String roleName = user.getRole().getName();
    		List<MenuDefBean> menu = new ArrayList<MenuDefBean>(); 
//    		if (roleName.equals(SysParams.adminRoleName)) {
//    			menu = SysConfig.getInstance().getMenu();
//    		}
//    		else {
//    			menu = menuDefService.getMenuListByRole(user.getRole().getID());	
//    		}
    		//将当前用户绑定的menu放入session
    		menu = menuDefService.getMenuListByRole(user.getRole().getId());
    		session.setAttribute("userMenus", menu);
    		//将当前用户绑定的site放入session
    		List<SiteBean> sites = userService.getUserSites(user.getId());
    		session.setAttribute("userSites", sites);
    		Map<String, List<SiteItemBean>> siteItems = 
    				new HashMap<String, List<SiteItemBean>>();
    		for (int i = 0; i < sites.size(); i++) {
    			String siteId = sites.get(i).getId();
    			siteItems.put(siteId, itemService.getSiteItemBySiteID(siteId));
    		}
    		session.setAttribute("siteItems", siteItems);
    		return "accountValid";
    	}
    	else {
    		return "accountInvalid";
    	}
	}
	
	@RequestMapping(value="/checkCode")
	public @ResponseBody String checkCode(@RequestParam("veryCode") String veryCode, HttpSession session)
	{
		String validateC = (String) session.getAttribute("validateCode");         
        if(veryCode==null||"".equals(veryCode)){     
            //out.println("<script type='text/javascript'>alert('验证码为空!');return false;</script>");
        	return "CertNull";
        }else{     
            if(validateC.toLowerCase().equals(veryCode.toLowerCase())){   
            	return "CertSuccess";
            }else{     
                //out.println("<script type='text/javascript'>alert('验证码错误!');return false;</script>");    
            	return "CertError";
            }     
        }  
	}
	
	@RequestMapping(value="/curUser")
	public @ResponseBody UserBean getCurUser(HttpSession session) {
		UserBean result = (UserBean)session.getAttribute("user");
		if (result.getLongitude()==0) result.setLongitude(SysParams.mapLongitude);
		if (result.getLatitude()==0) result.setLatitude(SysParams.mapLatitude);
		return result;
	}
	
	//获取与该user相关的所有sites
	@RequestMapping(value="/getUserSites")
	public @ResponseBody List<SiteBean> getUserSites(HttpSession session) {
		return (List<SiteBean>)session.getAttribute("userSites");
	}
	
	//获取与该user相关的所有site的最新状态，因为gps位置可能变更
	@RequestMapping(value="/getCurrentUserSites")
	public @ResponseBody List<SiteBean> getCurrentUserSites(HttpSession session) {
		UserBean user = (UserBean)session.getAttribute("user");
		String userid = user.getId();
		return userService.getUserSites(userid);
	}
	
	//public @ResponseBody List<SiteBean> getUserSites(HttpSession session) {
	//	UserBean user = (UserBean)session.getAttribute("user");
	//	String userid = user.getId();
	//	return userService.getUserSites(userid);
	//}
}
